﻿using System;
using System. Collections. Generic;
using System. Linq;
using System. Net;
using System. Windows;
using System. Xml. Linq;
using Microsoft. Phone. Controls;
using Microsoft. Phone. Shell;
using NextApp. WP7. AppConfig;
using NextApp. WP7. Models;
using System. Text. RegularExpressions;
using HtmlAgilityPack;

namespace NextApp. WP7. Util
{
    public static class Tool
    {
        #region 创建 Tile 静态方法
        public static void CreateShellTile(Post p)
        {
            ShellTile tile = ShellTile. ActiveTiles. FirstOrDefault(t => t. NavigationUri. ToString( ). Contains(string. Format("post={0}", p. id)));
            //表示已经有重复的项目
            if ( tile == null )
            {
                StandardTileData tileData = new StandardTileData
                {
                    Title = p. title,
                    Count = p. commentCount,
                    BackTitle = p. author,
                    BackContent = p. title,
                };
                //创建完成后 会直接跳转到开始菜单
                ShellTile. Create(new Uri(string. Format("/View/PostDetail.xaml?post={0}", p. id), UriKind. Relative), tileData);
            }
            else
            {
                MessageBox. Show("此文章已经被订到桌面上了");
            }
        }

        public static void CreateShellTile(Catalog c)
        {
            ShellTile tile = ShellTile. ActiveTiles. FirstOrDefault(t => t. NavigationUri. ToString( ). Contains(string. Format("catalog={0}", c. id)));
            //表示已经有重复的项目
            if ( tile == null )
            {
                StandardTileData tileData = new StandardTileData
                {
                    Title = c. name,
                    BackTitle = c. name,
                    BackContent = c. description,
                };
                //创建完成后 会直接跳转到开始菜单
                ShellTile. Create(new Uri(string. Format("/View/Posts.xaml?catalog={0}&title={1}", c. id, c. name), UriKind. Relative), tileData);
            }
            else
            {
                MessageBox. Show("此分类已经被订到桌面上了");
            }
        }

        #endregion

        #region 登入注销的处理
        public static void Login()
        {
            ( Application. Current. RootVisual as PhoneApplicationFrame ). Navigate(new Uri("/View/Login.xaml", UriKind. Relative));
        }

        public static void Logout( )
        {
            //注意这里只能将字符串设置为 string.Empty 而不是 null
            Config. Instance. Cookie = string. Empty;
            MessageBox. Show("已经成功注销");
        }

        public static void CheckAppBar( PhoneApplicationPage page )
        {
            page. ApplicationBar = Config. Instance. IsLogin ?
                page. Resources[ "appbar_Logout" ] as ApplicationBar :
                page. Resources[ "appbar_Login" ] as ApplicationBar;
        }
        #endregion

        #region 点击 发表文章 的按钮事件
        public static void AddPost_Click( )
        {
            if ( DataSingleton.Instance.catalogs.IsNotNullOrEmpty() )
            {
                //如果已经登陆
                if ( Config. Instance. IsLogin )
                {
                    //跳转到写文章页
                    ( Application. Current. RootVisual as PhoneApplicationFrame ). Navigate(new Uri("/View/AddPost.xaml", UriKind. Relative));
                }
                else
                {
                    if ( MessageBox. Show("请您先登陆 才能发表文章", "请登陆", MessageBoxButton. OKCancel) == MessageBoxResult. OK )
                    {
                        ( Application. Current. RootVisual as PhoneApplicationFrame ). Navigate(new Uri("/View/Login.xaml?next=addpost", UriKind. Relative));
                    }
                }
            }
        }
        #endregion

        #region 非 Catalog 控件加载Catalogs
        public static void LoadCatalogs( )
        {
            WebClient client = new WebClient( );
            client. Headers[ "User-Agent" ] = Config. Instance. Http_User_Agent;
            client. DownloadStringCompleted += (s, e1) =>
            {
                if ( e1. Error != null )
                {
                    MessageBox. Show("添加文章分类失败", "网络错误", MessageBoxButton. OK);
                    return;
                }
				XElement nextApp;
				try
				{
					nextApp = XElement. Parse(e1. Result);
				}
				catch ( Exception )
				{
					return;
				}
                Catalog[ ] catalogs = nextApp. Elements("catalogs") == null ?
                    null :
                    nextApp. Elements("catalogs"). Elements("catalog"). Select(
                    c =>
                    {
                        Dictionary<string, string> attributes = c. Attributes( ). ToDictionary(a => a. Name. LocalName, a => a. Value);
                        return new Catalog
                        {
                            description = attributes[ "description" ],
                            id = attributes[ "id" ]. ToInt32( ),
                            name = attributes[ "name" ],
                        };
                    }). ToArray( );
                //保存起来
                DataSingleton. Instance. catalogs = catalogs;
            };
            //异步加载
            if ( NextAppSingleton.Instance.url_catalog_list.IsNotNullOrWhitespace() )
            {
                client. DownloadStringAsync(new Uri(Config. Instance. GetApi(string. Format("{0}&guid={1}", NextAppSingleton. Instance. url_catalog_list, Guid. NewGuid( ))), UriKind. Absolute));
            }
            
        }
        #endregion

		#region 横向与竖向转换处理
		public static void PrepareToOrientation(this PhoneApplicationPage page)
		{
			page. OrientationChanged += (s, e) =>
				{
					switch ( e.Orientation )
					{
						case PageOrientation. Landscape:
						case PageOrientation. LandscapeLeft:
						case PageOrientation. LandscapeRight:
							page. ApplicationBar. Mode = ApplicationBarMode. Default;
							break;
						case PageOrientation. Portrait:
						case PageOrientation. PortraitDown:
						case PageOrientation. PortraitUp:
							page. ApplicationBar. Mode = ApplicationBarMode. Minimized;
							break;
					}
				};
		}
		#endregion
		
		#region  浏览器缩放图片处理
		public static string ProcessHTMLString(string sourceHTML)
		{
			//然后转码
			HtmlDocument document = new HtmlDocument( );
			document. LoadHtml(sourceHTML);
			if ( document == null )
			{
				return sourceHTML;
			}
			var images = document. DocumentNode. SelectNodes("//img");
			if ( images == null )
			{
				return sourceHTML;
			}
			foreach ( HtmlNode image in images )
			{
				if ( image. Attributes[ "width" ] != null )
				{
					//修改高宽
					int width = GetNumFromString(image. Attributes[ "width" ]. Value);
					if ( width > 0 )
					{
						image. Attributes[ "width" ]. Value = width. ToString( );
					}
					else
					{
						image. Attributes[ "width" ]. Remove( );
					}
				}
				if ( image. Attributes[ "height" ] != null )
				{
					image. Attributes[ "height" ]. Remove( );
				}
			}
			return document. DocumentNode. InnerHtml;
		}
		private static int GetNumFromString(string originStr)
		{
			string num_str = Regex. Replace(originStr, @"[^\d]*", "");
			int num;
			if ( int. TryParse(num_str, out num) )
			{
				return num <= 480 ? num * 2 : 960;
			}
			else
			{
				return -1;
			}
		}
		#endregion
	}
}
